/* eslint-disable react/no-unused-state, no-plusplus */
import React, { Component } from 'react';
import { Table, Icon, Input, Button, Grid, Pagination, Progress, Dialog, Feedback } from '@icedesign/base';
import IceContainer from '@icedesign/container';
import { FormBinderWrapper, FormBinder, FormError, } from '@icedesign/form-binder';
/* 数据交互 */
import DataBinder from '@icedesign/data-binder';
/* 自定义API */
import { apiDelOne, apiAddOne, apiDelSelect } from '../../../../api/api';

const { Row, Col } = Grid;

const fromValue = {
  ip: '',
};

// DataBinder 配置
@DataBinder({
  // 获取服务器记录 配置
  dataTable: {
    url: 'http://127.0.0.1/scan/index.php/data/getServer',
    method: 'get',
    // method  post下是 data 参数，method get下是 params 参数
    params: {
      page: 1,
    },
    // 默认值
    // defaultBindingData: {
    //   currentPage: 1,
    //   pageSize: 5,
    //   total: 15,
    //   list: [],
    // },
  },
})

export default class ServerList extends Component {
  static displayName = 'ServerList';
  static propTypes = {};
  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      value: fromValue,
    };
  }

  // DataBinder 不会在组件初始化的时候帮你自动请求一次
  componentDidMount() {
    // 取第一页 数据
    this.props.updateBindingData('dataTable', {
      params: {
        page: 1,
      },
    });
  }

  // 翻页
  handlePaginationChange = (currentPage) => {
    this.props.updateBindingData('dataTable', {
      params: {
        page: currentPage,
      },
    });
  };

  // 进度条
  renderProgress = (value) => {
    return <Progress percent={parseInt(value)} />;
  };

  // 操作
  renderOper = (value, index, record) => {
    return (
      <div style={styles.oper} onClick={this.delOne.bind(this, record)}>
        <Icon
          type="ashbin"
          size="small"
          style={{ ...styles.icon, ...styles.deleteIcon }}
        />
      </div>
    );
  };

  // 删除一条
  delOne = (record) => {
    Dialog.confirm({
      content: '确定删除吗?',
      title: '删除',
      locale: {
        ok: '确认',
        cancel: '取消',
      },
      onOk: async () => {
        let response = await apiDelOne(record.id);
        if(response === 'success'){
          // 删除完成, 重新渲染
          this.handlePaginationChange(1);
        }
      },
    });
  };

  // 选择改变的时候触发的事件
  onChange = (ids) => {
    this.ids = ids;
  };

  // 删除选中项
  delSelect = () => {
    if (this.ids === undefined || this.ids.length == 0) {
      Dialog.alert({
        content: '没有选择机器！！！',
        closable: false,
        title: '提示',
      });
    } else {
      Dialog.confirm({
        content: '确定批量删除吗?',
        title: '删除',
        locale: {
          ok: '确认',
          cancel: '取消',
        },
        onOk: async () => {
          let response = await apiDelSelect(this.ids.join(','));
          if(response === 'success'){
            // 删除完成, 重新渲染
            this.handlePaginationChange(1);
          }
        },
      });
    }
  }

  // 新增提交
  addServer = () => {
    this.refForm.validateAll((error, values) => {
      if (error) {
        // show validate error
        return false;
      }
      this.add(values.ip);
    });
  };

  // 为了获得 添加返回结果
  async add(ip) {
    let response = await apiAddOne(ip);
    if(response === 'success'){
      // 成功 重新渲染
      this.handlePaginationChange(1);
    }
  }

  // 数据改变,设置值
  onFormChange = (value) => {
    this.setState({
      value,
    });
  }

  render() {
    // 获取绑定的数据
    const dataTable = this.props.bindingData.dataTable;

    return (
      <IceContainer title="机器列表">
        <FormBinderWrapper
          ref={(ref) => {
            this.refForm = ref;
          }}
          value={this.state.value}
          onChange={this.onFormChange}
        >
          <div style={styles.dialogContent}>
            <Row wrap style={styles.headRow}>
              <Col l="8" style={styles.formCol}>
                <span style={styles.label}>IP:</span>
                <FormBinder
                  required
                  min={7}
                  max={15}
                  message="IP地址不能为空"
                >
                  <Input style={styles.input}
                    name="ip"
                    placeholder="请输入IP地址"
                  />
                </FormBinder>
                <FormError name="ip" />
              </Col>
              <Col>
                <Button type="primary" style={styles.button} onClick={this.addServer}>
                  <Icon type="add" size="xs" style={{ marginRight: '4px' }} />添加机器
                </Button>
                <Button type="primary" shape="warning" style={{ ...styles.button, marginLeft: 10 }} onClick={this.delSelect}>
                  <Icon type="ashbin" size="xs" style={{ marginRight: '4px' }} />批量删除机器
                </Button>
              </Col>
            </Row>
          </div>
        </FormBinderWrapper>
        <Table
          // 表格数据源
          dataSource={dataTable.list}
          // loading 加载
          isLoading={dataTable.__loading}
          // 复选框
          rowSelection={{ onChange: this.onChange }}
        >
          <Table.Column title="ID" dataIndex="id" width={50} />
          <Table.Column title="IP" dataIndex="ip" width={150} />
          <Table.Column title="CPU" dataIndex="cpu" width={50} />
          <Table.Column title="内存" dataIndex="ram" width={50} />
          <Table.Column title="网络" dataIndex="network" width={50} />
          <Table.Column title="进度" dataIndex="progress" cell={this.renderProgress} width={150} />
          <Table.Column title="操作" width={80} cell={this.renderOper} />
        </Table>
        <Pagination
          // 分页样式
          style={styles.pagination}
          // 当前页
          current={dataTable.currentPage}
          // 每页几条
          pageSize={dataTable.pageSize}
          // 总条数
          total={dataTable.total}
          // 翻页
          onChange={this.handlePaginationChange}
        />
      </IceContainer>
    );
  }
}

const styles = {
  headRow: {
    marginBottom: '10px',
  },
  icon: {
    color: '#2c72ee',
    cursor: 'pointer',
  },
  deleteIcon: {
    marginLeft: '20px',
  },
  button: {
    borderRadius: '4px',
  },
  pagination: {
    marginTop: '20px',
    textAlign: 'right',
  },
  dialogContent: {},
  formRow: {
    marginTop: '20px',
  },
  input: {
    width: '80%',
  },
  formCol: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '20px',
  },
  label: {
    lineHeight: '28px',
    paddingRight: '10px',
  },
};
